{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "9d19e2b7",
   "metadata": {},
   "source": [
    "## numpy的其他补充函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "ff589914",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b137ab64",
   "metadata": {},
   "source": [
    "1. np.apply_along_axis:沿着某个轴执行某个函数\n",
    "\n",
    "例如自定义函数(def),可以通过这个函数作用给数组中的某个值。类似与map函数。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "795e8b6b",
   "metadata": {},
   "source": [
    "apply_along_axis(func1d, axis, arr, *args, **kwargs)\n",
    "\n",
    "* func1d:函数名称，自建函数或者是内置函数 \n",
    "* axis:函数作用的轴。传入轴当作参数传给函数。\n",
    "* arr:传入的数组\n",
    "* return:函数的返回值，是将输入函数每次返回值放在数组中统一进行返回"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "033e8483",
   "metadata": {},
   "outputs": [],
   "source": [
    "#  自定义函数：这对数组求除掉最大值、最小值之外数据的平均值\n",
    "def a_mean(a_array):\n",
    "    b_array=a_array[(a_array!=a_array.max())&(a_array!=a_array.min())]\n",
    "    the_mean = b_array.mean()\n",
    "    return the_mean"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "ddd1b45c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[15, 13, 14,  7,  1],\n",
       "       [11,  6, 15,  2,  0],\n",
       "       [ 1, 14,  0, 10, 10]])"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "d = np.random.randint(0,18,size=(3,5))\n",
    "d"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "8fc36446",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([11.33333333,  6.33333333,  7.        ])"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.apply_along_axis(a_mean,axis=1,arr=d)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "011ec3a5",
   "metadata": {},
   "source": [
    "2. np.linspace(),将输入两个数区间平均分为几份"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "530e6988",
   "metadata": {},
   "source": [
    "linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)\n",
    "\n",
    "Parameters\n",
    "    ----------\n",
    "    start : 开始数，The starting value of the sequence.\n",
    "    stop : 终止数\n",
    "        The end value of the sequence, unless `endpoint` is set to False.\n",
    "    num : int, optional\n",
    "        Number of samples to generate. Default is 50. Must be non-negative.\n",
    "    endpoint : bool, optional\n",
    "        If True, `stop` is the last sample. Otherwise, it is not included.\n",
    "        Default is True.\n",
    "    retstep : bool, optional\n",
    "        If True, return (`samples`, `step`), where `step` is the spacing\n",
    "        between samples.\n",
    "    dtype : dtype, optional\n",
    "        The type of the output array.  If `dtype` is not given, the data type\n",
    "        is inferred from `start` and `stop`. The inferred dtype will never be\n",
    "        an integer; `float` is chosen even if the arguments would produce an\n",
    "        array of integers.\n",
    "    \n",
    "    Returns\n",
    "    -------\n",
    "    samples : ndarray,返回值一般为ndarray数组"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "4e74c2bc",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0. , 4.5, 9. ])"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.linspace(0,9,3)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3098182b",
   "metadata": {},
   "source": [
    "3. np.unique返回数组中的唯一值"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e3fe6659",
   "metadata": {},
   "source": [
    "unique(ar, return_index=False, return_inverse=False, return_counts=False, axis=None)\n",
    "\n",
    "参数说明:\n",
    "ar:传入的数组\n",
    "return_counts:出现数据对应出现的次数。此时返回两个数组，即唯一数数组和出现次数数组。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "368f62df",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[8, 4, 3, 1],\n",
       "       [4, 2, 6, 8],\n",
       "       [3, 7, 0, 6],\n",
       "       [3, 0, 0, 0]])"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "d2 = np.random.randint(0,9,size=(4,4))\n",
    "d2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "59d990b9",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0, 1, 2, 3, 4, 6, 7, 8])"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#返回所有数组中出现的唯一值\n",
    "np.unique(d2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "f61e4170",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(array([0, 1, 2, 3, 4, 6, 7, 8]), array([4, 1, 1, 3, 2, 2, 1, 2]))"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#在np.unique函数中传入return_counts=True参数之后，返回元组中包含两个数组。\n",
    "#一个数组是唯一值数组，另一个是唯一值对应的出现次数。\n",
    "np.unique(d2,return_counts=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "c7615530",
   "metadata": {
    "collapsed": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Help on function unique in module numpy:\n",
      "\n",
      "unique(ar, return_index=False, return_inverse=False, return_counts=False, axis=None)\n",
      "    Find the unique elements of an array.\n",
      "    \n",
      "    Returns the sorted unique elements of an array. There are three optional\n",
      "    outputs in addition to the unique elements:\n",
      "    \n",
      "    * the indices of the input array that give the unique values\n",
      "    * the indices of the unique array that reconstruct the input array\n",
      "    * the number of times each unique value comes up in the input array\n",
      "    \n",
      "    Parameters\n",
      "    ----------\n",
      "    ar : array_like\n",
      "        Input array. Unless `axis` is specified, this will be flattened if it\n",
      "        is not already 1-D.\n",
      "    return_index : bool, optional\n",
      "        If True, also return the indices of `ar` (along the specified axis,\n",
      "        if provided, or in the flattened array) that result in the unique array.\n",
      "    return_inverse : bool, optional\n",
      "        If True, also return the indices of the unique array (for the specified\n",
      "        axis, if provided) that can be used to reconstruct `ar`.\n",
      "    return_counts : bool, optional\n",
      "        If True, also return the number of times each unique item appears\n",
      "        in `ar`.\n",
      "    \n",
      "        .. versionadded:: 1.9.0\n",
      "    \n",
      "    axis : int or None, optional\n",
      "        The axis to operate on. If None, `ar` will be flattened. If an integer,\n",
      "        the subarrays indexed by the given axis will be flattened and treated\n",
      "        as the elements of a 1-D array with the dimension of the given axis,\n",
      "        see the notes for more details.  Object arrays or structured arrays\n",
      "        that contain objects are not supported if the `axis` kwarg is used. The\n",
      "        default is None.\n",
      "    \n",
      "        .. versionadded:: 1.13.0\n",
      "    \n",
      "    Returns\n",
      "    -------\n",
      "    unique : ndarray\n",
      "        The sorted unique values.\n",
      "    unique_indices : ndarray, optional\n",
      "        The indices of the first occurrences of the unique values in the\n",
      "        original array. Only provided if `return_index` is True.\n",
      "    unique_inverse : ndarray, optional\n",
      "        The indices to reconstruct the original array from the\n",
      "        unique array. Only provided if `return_inverse` is True.\n",
      "    unique_counts : ndarray, optional\n",
      "        The number of times each of the unique values comes up in the\n",
      "        original array. Only provided if `return_counts` is True.\n",
      "    \n",
      "        .. versionadded:: 1.9.0\n",
      "    \n",
      "    See Also\n",
      "    --------\n",
      "    numpy.lib.arraysetops : Module with a number of other functions for\n",
      "                            performing set operations on arrays.\n",
      "    repeat : Repeat elements of an array.\n",
      "    \n",
      "    Notes\n",
      "    -----\n",
      "    When an axis is specified the subarrays indexed by the axis are sorted.\n",
      "    This is done by making the specified axis the first dimension of the array\n",
      "    (move the axis to the first dimension to keep the order of the other axes)\n",
      "    and then flattening the subarrays in C order. The flattened subarrays are\n",
      "    then viewed as a structured type with each element given a label, with the\n",
      "    effect that we end up with a 1-D array of structured types that can be\n",
      "    treated in the same way as any other 1-D array. The result is that the\n",
      "    flattened subarrays are sorted in lexicographic order starting with the\n",
      "    first element.\n",
      "    \n",
      "    .. versionchanged: NumPy 1.21\n",
      "        If nan values are in the input array, a single nan is put\n",
      "        to the end of the sorted unique values.\n",
      "    \n",
      "        Also for complex arrays all NaN values are considered equivalent\n",
      "        (no matter whether the NaN is in the real or imaginary part).\n",
      "        As the representant for the returned array the smallest one in the\n",
      "        lexicographical order is chosen - see np.sort for how the lexicographical\n",
      "        order is defined for complex arrays.\n",
      "    \n",
      "    Examples\n",
      "    --------\n",
      "    >>> np.unique([1, 1, 2, 2, 3, 3])\n",
      "    array([1, 2, 3])\n",
      "    >>> a = np.array([[1, 1], [2, 3]])\n",
      "    >>> np.unique(a)\n",
      "    array([1, 2, 3])\n",
      "    \n",
      "    Return the unique rows of a 2D array\n",
      "    \n",
      "    >>> a = np.array([[1, 0, 0], [1, 0, 0], [2, 3, 4]])\n",
      "    >>> np.unique(a, axis=0)\n",
      "    array([[1, 0, 0], [2, 3, 4]])\n",
      "    \n",
      "    Return the indices of the original array that give the unique values:\n",
      "    \n",
      "    >>> a = np.array(['a', 'b', 'b', 'c', 'a'])\n",
      "    >>> u, indices = np.unique(a, return_index=True)\n",
      "    >>> u\n",
      "    array(['a', 'b', 'c'], dtype='<U1')\n",
      "    >>> indices\n",
      "    array([0, 1, 3])\n",
      "    >>> a[indices]\n",
      "    array(['a', 'b', 'c'], dtype='<U1')\n",
      "    \n",
      "    Reconstruct the input array from the unique values and inverse:\n",
      "    \n",
      "    >>> a = np.array([1, 2, 6, 4, 2, 3, 2])\n",
      "    >>> u, indices = np.unique(a, return_inverse=True)\n",
      "    >>> u\n",
      "    array([1, 2, 3, 4, 6])\n",
      "    >>> indices\n",
      "    array([0, 1, 4, 3, 1, 2, 1])\n",
      "    >>> u[indices]\n",
      "    array([1, 2, 6, 4, 2, 3, 2])\n",
      "    \n",
      "    Reconstruct the input values from the unique values and counts:\n",
      "    \n",
      "    >>> a = np.array([1, 2, 6, 4, 2, 3, 2])\n",
      "    >>> values, counts = np.unique(a, return_counts=True)\n",
      "    >>> values\n",
      "    array([1, 2, 3, 4, 6])\n",
      "    >>> counts\n",
      "    array([1, 3, 1, 1, 1])\n",
      "    >>> np.repeat(values, counts)\n",
      "    array([1, 2, 2, 2, 3, 4, 6])    # original order not preserved\n",
      "\n"
     ]
    }
   ],
   "source": [
    "help(np.unique)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
